上一章我們用 Structural Directive 來新增、刪除 DOM 元素(節點),而 Attribute directives 可以改變 DOM Property、 HTML Attribute ...等等。像我們之前用的 ngModel 就是預設的一種 Attribute directives。
接下來我們要介紹的是 ngStyle 和 ngClass。
我們通常可以用 inline 的方式來設定樣式,也就是將css直接塞在 html 的標籤內,像這樣:
// homepage.component.html
<h1 style="color: red">ngStyle</h1>

但如果我今天想要動態修改字體顏色呢,我一開始的想法是這樣:
// homepage.component.ts
color1 = 'red';
// homepage.component.html
<h1 style="color: {{color1}}">ngStyle</h1>

好的馬上出現錯誤,那我們換一條路,我把 color: 'red' 這整段字串塞進style裡面:
// homepage.component.ts
color1 = 'color : \'red\';'; // color: 'red';
// homepage.component.html
<h1 style="color: {{color1}}">ngStyle</h1>

恩,看起來也很母湯,這時我們可以用 ngStyle 來幫我們動態指定樣式。
善用 snippets 新增程式碼,

會幫我們產生這樣的程式碼:
<h1 [ngStyle]="{style: expression}"></h1>
style 跟 expression是我們要修改的部分。
style 我填入 color, expression 填入我放在 ts 的變數 color1。
// homepage.component.ts
color1 = 'green';
// homepage.component.html
<h1 [ngStyle]="{color: color1}"></h1>

這樣就能自己修改顏色的值了,那假如我要改的樣式很多,我也可以把 {color: color1} 這整段放在 ts 裡,並多加一些 style。改一下變數名稱,我命名為styles:
// homepage.component.html
<h1 [ngStyle]="styles">ngStyle</h1>
// homepage.component.ts
styles = {
'background-color': 'black',
color: 'red'
};
這邊 'background-color' 被要求加上單引號,是因為中間的「減號」會被當作是前後兩個變數相減,語法會解析錯誤。像color就不需要加上單引號。
那麼看看效果:

那如果我想做一個「按一下就能改變顏色」的功能,我只要多綁一個事件在 <h1>這個標籤上就可以了。
// homepage.component.html
<h1 [ngStyle]="styles" (click)="styles.color='green'">ngStyle</h1>
結果如下:

如果你真的很不想用 ngStyle ,下面這種方式也是可以的,將變數直接綁定到 style.color :
// homepage.component.html
<h1 [style.color]= "color1">ngStyle</h1>
// homepage.component.ts
color1 = 'red';
至於要用哪種方式,則由個人喜好。
ngClass 的語法其實和 ngStyle 類似。先透過 Snippet 新增程式碼:
[ngClass]="{cssClass: expression}"
cssClass就放一個css的class,expression 呢,可以放一個 boolean 的式子,我先在 homepage.component.css 定義一個 css 的 class ,命名為 .COLOR:
// homepage.component.css
.COLOR {
color: gray;
}
然後我新增一個變數 type ,以及一個輸入框,用 Two-way Binding 綁定 type 變數。ngClass 的 expression,我填入 type == '123',也就是當我的輸入框輸入 123 時,字才會變成灰色,而輸入其他字,字都會是黑色。
// homepage.component.html
<input type="text" [(ngModel)]="type"><br>
<h1 [ngClass]="{'COLOR': type == '123' }" >ngClass</h1>
// homepage.component.ts
type = '';
結果如下:

當然,和 ngStyle 一樣,你也可以這樣寫:
<h1 [class.COLOR]="type == '123'" >ngClass</h1>
效果是一樣的。